//
//  LKComposeViewController.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 2016/10/8.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
import SVProgressHUD
class LKComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor  = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        setNavBar()
        setTextView()
        setToolBar()
        setImagePickerView()
        self.view.bringSubview(toFront: toolBar)
        registerNotification()
    }
    //视图将要显示的时候
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if imagePicker.images.count != 0 {
            //设置图片选择视图的显示
            imagePicker.view.isHidden = false
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    internal func close() {
        dismiss(animated: true, completion: nil)
    }
    //发布微博按钮懒加载
    internal lazy var sendBtn : UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        btn.setTitle("发送", for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        let barButtonitem = UIBarButtonItem(customView: btn)
        barButtonitem.isEnabled = false
        return barButtonitem
    }()
    //懒加载textView
    internal lazy var textView : UITextView = {
        let textView  = UITextView()
        textView.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.textColor = UIColor.darkGray
        textView.delegate = self
        textView.alwaysBounceVertical = true
        return textView
    }()
    //懒加载占位符
    internal lazy var placeHolderLable: UILabel = UILabel(title: "老王你妈妈喊你回家吃饭!", font: 16, textColor: UIColor.lightGray)
    //懒加载底部工具栏
    internal lazy var toolBar: UIToolbar = {
        let tb = UIToolbar()
        var items = [UIBarButtonItem]()
        //添加五个按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for value in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named:value.element), for: .normal)
            btn.setImage(UIImage(named: value.element + "_highlighted"), for: .highlighted)
            //设置下标
            btn.tag = value.offset
            //添加点击事件
            btn.addTarget(self, action: #selector(toolBarBtnItemDicClick(btn:)), for: .touchUpInside)
            btn.sizeToFit()
            let barItem = UIBarButtonItem(customView: btn)
            //添加到数组之中
            items.append(barItem)
            //添加等宽弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        tb.items = items
        return tb
    }()
    //懒加载图片选择视图控制器
    lazy var imagePicker : LKImagePickerViewController = {
        //实例化流水布局属性
        let flowLayout = UICollectionViewFlowLayout()
        //设置属性
        flowLayout.itemSize = CGSize(width:imagePickerItemW, height: imagePickerItemW)
        flowLayout.minimumLineSpacing = imagePickerCellMargin
        flowLayout.minimumInteritemSpacing = imagePickerCellMargin
        flowLayout.sectionInset = UIEdgeInsets(top: imagePickerCellMargin, left: imagePickerCellMargin, bottom: 0, right: imagePickerCellMargin)
        //实例化控制器
        let imagePickerVC = LKImagePickerViewController(collectionViewLayout: flowLayout)
        imagePickerVC.collectionView?.backgroundColor = UIColor.white
        return imagePickerVC
    }()
    lazy var keyboardView : LKEmotionKeyboardView = {
        let kv = LKEmotionKeyboardView()
        kv.frame = CGRect(x: 0, y: 0, width: 0, height: emotionKeyboardHeight)
        return kv
    }()
    //按钮点击方法实现
    @objc private func sendBtnDidClick () {
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        //在数组和字典中不能够直接添加隐式的可选类型
        let parameters = ["access_token" : LKUserInforViewModel.sharedUserInfoViewModel.userInfoModel?.access_token ?? "" ,
                          "status" : textView.text ?? ""]
        if imagePicker.images.count == 0 {
            //没有图片则发布文字微博
            LKNetworkTool.sharedTool.request(method: .Post, urlString: urlString, parameters: parameters) { (_, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发布微博成功,棒棒哒!")
            }
        }
        else {
            //发布图片微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            LKNetworkTool.sharedTool.post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
                //拼接要上传的二进制文件到formData中
                let imageData = UIImagePNGRepresentation(self.imagePicker.images.last!)
                formData.appendPart(withFileData: imageData!, name: "pic", fileName: "hdhdhdhdh", mimeType: "application/octet-stream")
                }, progress: nil, success: { (_, _) in
                    SVProgressHUD.showSuccess(withStatus: "发布图片微博成功,棒棒哒!")
                }, failure: { (_, error) in
                    print(error)
                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
            })
        }
        
    }
    //底部工具栏按钮点击方法实现
    @objc private func toolBarBtnItemDicClick (btn:UIButton) {
        switch btn.tag {
        case 0:
            //手动调用协议方法
            imagePicker.userWillAddImage()
        case 1:
            SVProgressHUD.showInfo(withStatus: "@老王")
        case 2:
            SVProgressHUD.showInfo(withStatus: "话题")
        case 3:
//            SVProgressHUD.showInfo(withStatus: "表情")
            //使用自定义的键盘,即使用inputView
            //当系统键盘已经成为第一响应者的时候是无法进行替换的
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            textView.inputView = textView.inputView == nil ? keyboardView : nil
            textView.reloadInputViews()
        case 4:
            SVProgressHUD.showInfo(withStatus: "更多")
        default:
            SVProgressHUD.showInfo(withStatus: "你是傻逼吗")
        }
    }
    //注册监听者
    private func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    //监听到通知响应方法的实现
    @objc private func keyBoardWillChange (notification: Notification){
        //获得键盘弹出后的frame
        let endFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue) .cgRectValue
        //更新toolBar 的约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(endFrame.origin.y - ScreenHeight)
        }
        //添加动画时间
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
    }
    //移除观察者
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK:UI 相关设置的分类
extension LKComposeViewController {
    //设置导航栏
    internal func setNavBar () {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(action: #selector(close), target: self, title: "关闭")
        self.navigationItem.rightBarButtonItem = sendBtn
        //自定义titleView
        let titleLabel = UILabel(title: "", font: 16, textColor: UIColor.darkGray)
        //设置标签属性
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        var titleText = "发布微博"
        //        let name = LKUserInforViewModel.sharedUserInfoViewModel.userInfoModel?.name
        //判断用户名是否为空
        if let name = LKUserInforViewModel.sharedUserInfoViewModel.userInfoModel?.name {
            //不为空,拼接
            titleText = "发布微博\n\(name)"
            //设置富文本属性
            //实例化可变的属性文本
            let strM = NSMutableAttributedString(string: titleText)
            //给可变的属性文本添加属性
            let range = (titleText as NSString).range(of: name)
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName: UIColor.orange], range: range)
            titleLabel.attributedText = strM
        }else{
            //为空
            titleLabel.text = titleText
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
    //设置textView
    internal func setTextView () {
        //添加子控件
        self.view.addSubview(textView)
        //设置约束
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(ScreenHeight / 3)
        }
        textView.addSubview(placeHolderLable)
        placeHolderLable.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(5)
        }
    }
    //设置底部工具栏
    internal func setToolBar () {
        self.view.addSubview(toolBar)
        toolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(36)
        }
    }
    //设置图片选择视图
    internal func setImagePickerView () {
        //添加子视图控制器,保证modal的时候不会被释放
        self.addChildViewController(imagePicker)
        self.view.addSubview(imagePicker.view)
        //设置约束
        imagePicker.view.snp.makeConstraints { (make) in
            make.bottom.right.left.equalTo(self.view)
            make.height.equalTo(ScreenHeight * 2 / 3)
        }
        //设置隐藏
        imagePicker.view.isHidden = true
    }
}

extension LKComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //根据文本是否有内容设置按钮是否可用
        self.sendBtn.isEnabled = textView.hasText
        //根据内容设置占位符是否隐藏
        self.placeHolderLable.isHidden = textView.hasText
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}









